
import M from "./m";
import MediaComponent from "./single";
class MediaGroupComponent extends M {
  componentName = 'mediaGroup';
  meta_type = 'image';
  medias: Array<MediaComponent> = [new MediaComponent({})];
  max_group: number = 15;
  get length() {
    return this.medias.length;
  }
  materia_form() {
    return [{
      name: '素材',
      key: 'mediaGroup',
      rules: () => {
        return this.media_restriction;
      },
      min: this.length,
      values: []
    }]
  }
  query() {
    const query = this.medias.map(media => {
      const q = media.query();
      if (this.name === 'element_story') {
        return {
          image: q.image_id
        }
      }
      return q;
    })
    return {
      list: query
    };
  }

  empty() {
    this.medias = [];
  }

  isEmpty() {
    return !!this.medias.find(_ => !_.media_url);
  }

  mediaMap(_function: Function): Array<any> {
    return this.medias.map(media => _function(media));
  }

  setSrc(options: { keyFrameImageUrl: string, media_id: string, media_url: string, meta_type: string, cover_id: string, number: number }) {
    const media = this.medias[options.number];
    media.setSrc(options);
  }

  checkMetaType(component: any) {
    const { name } = component;
    if (name === 'image_list') return 'image';
    if (name === 'video_list') return 'video';
    if (name === 'element_story') return 'image';
    return 'unknown';
  }
  // image_list.list.image_id
  // image_list.list.video_id
  // element_story.list.image
  constructor(options: any) {
    super(options);
    this.init(options);
    if (options.children) {
      this.tx_component = options.name;
      this.meta_type = this.checkMetaType(options);
      const children = options.children;
      const list = children.list;
      const array_property = (children.list ? (children.list.array_property || {}) : {}) as any;

      // 多图
      const medias = new Array((array_property).min_number || 1).fill(0).map(_ => new MediaComponent({
        ...list,
        // 重写name
        name: this.meta_type,
      }));
      if (medias[0]) {
        this.media_restriction = medias[0].media_restriction
      }
      this.medias = medias;
    }
  }
}

export default MediaGroupComponent
